package com.wms.service.impl;

import com.alibaba.excel.EasyExcel;
import com.wms.entity.OutStockDetail;
import com.wms.entity.OutStockReport;
import com.wms.mapper.OutTaskMapper;
import com.wms.minio.MinioPojo;
import com.wms.service.OutTaskService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.List;
import java.util.Map;

@Service
public class OutTaskServiceImpl implements OutTaskService {
    @Autowired
    OutTaskMapper outTaskMapper;
//    @Autowired
//    //获取服务器地址
//    HttpServletRequest request;

    // MinIO配置参数，从配置文件读取


    @Autowired
    private MinioClient minioClient;
    // 注入MinIO配置参数（包含桶名等信息）
    @Autowired
    private MinioPojo minioPojo;

    ServletContext servletContext;
    public OutTaskServiceImpl(ServletContext servletContext){
        this.servletContext=servletContext;
    }

    @Scheduled(cron = "0 0 9 * * ?")
    @Override
    @Transactional
    public void generateReport() {
      try {
        List<OutStockDetail> list=outTaskMapper.export();
        System.out.println(list);

//        //获取服务器地址
//        String root=servletContext.getRealPath("/");
//        File dir=new File(root+"/stock");
//        if (!dir.exists())
//            dir.mkdir();
//        //文件名
//        String fileName=System.currentTimeMillis()+".xlsx";
//        EasyExcel.write(dir.getAbsoluteFile()+"/"+fileName, OutStockDetail.class)
//                .sheet("出库明细")
//                .doWrite(()->{
//                    return list;
//                });
//        //服务器存储地址
//        String path="/stock/"+fileName;
//        System.out.println("服务器存储地址："+path);
//        System.out.println("本机存储地址："+dir);


        // 生成Excel文件到内存
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        EasyExcel.write(outputStream, OutStockDetail.class)
                .sheet("出库明细")
                .doWrite(list);

        // 准备上传到MinIO的参数
        String fileName = "stock/" + System.currentTimeMillis() + ".xlsx"; // 存储路径+文件名

        // 上传文件到MinIO（使用注入的minioClient）
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(minioPojo.getBucketName()) // 从配置获取桶名
                        .object(fileName)
                        .stream(new ByteArrayInputStream(outputStream.toByteArray()),
                                outputStream.size(),
                                -1)
                        .contentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                        .build()
        );

        // 关闭输出流
        outputStream.close();

        // 存储到数据库的URL（MinIO访问路径，结合配置的URL和桶名）
        String reportUrl = minioPojo.getUrl() + "/" + minioPojo.getBucketName() + "/" + fileName;
        System.out.println("MinIO存储地址：" + reportUrl);
        OutStockReport report=new OutStockReport();


        //报表提交到数据库
          //定义文件名称
        List<Map<String, Object>> timeMapList = outTaskMapper.NAtime();
        String newTime = "未知时间";
        if (timeMapList != null && !timeMapList.isEmpty()) {
            Map<String, Object> dateMap = timeMapList.get(0);
            String currentDate = dateMap.get("current_dt") != null ? dateMap.get("current_dt").toString() : "";
            String sevenDaysAgo = dateMap.get("seven_days_ago") != null ? dateMap.get("seven_days_ago").toString() : "";
            newTime =sevenDaysAgo  + "~" + currentDate;
        }

        report.setReportDate(newTime);
        report.setReportUrl(reportUrl);
        report.setType(1);
        int n=outTaskMapper.addExcel(report);
        System.out.println("-----------自动执行发生-------------");

      } catch (Exception e) {
          System.err.println("生成报表并上传到MinIO失败：" + e.getMessage());
          e.printStackTrace();
      }
    }



    @Override
    public List<Map<String,Object>> baobiao() {
        return outTaskMapper.baobiao();
    }
}
